import React from 'react';
import { observer, inject } from 'mobx-react';
import { toJS } from 'mobx';
import classnames from 'classnames';
import { withRouter } from 'react-router-dom';
import { Tools, WingBlank, WhiteSpace, Avatar, Flex, Icon, Result } from 'weaver-mobile';
import { ListViewPage } from 'weaver-mobile-page';
import { renderLoading, renderNoData } from '../public/BlogUtils';
import AttentionTool from '../public/AttentionTool';
import BlogComment from '../public/BlogComment';
import NewAttentionTool from '../public/NewAttentionTool'
const getLabel = Tools.getLabel;

@withRouter
@inject('blogHomeStore')
@observer
export default class HisBlog extends React.Component {
  static defaultProps = {
    prefixCls: 'blog-center-hisblog'
  }

  constructor(props) {
    super(props);
    this.updateHisAttentionStatus = this.updateHisAttentionStatus.bind(this);
		this.state = {
      userId: props.userId || null,
      cardType: 1,
    }
  }

  componentWillMount() {
    const { store: { inital }, location: { pathname } } = this.props;
    inital(pathname)
  }

  componentDidMount() {
    const { store: { getBlogPersonalInfo, setUid }, userId, location: { pathname } } = this.props;
    let id = pathname.split('/');
        id = id[id.length-1];
    userId ? setUid(userId) : setUid(id);
    this.setState({userId: id})
    getBlogPersonalInfo({blogId: id});
  }

  componentWillUnmount() {
    const { store } = this.props;
		store.clear();
  }

  // 更新他的微博关注状态
  updateHisAttentionStatus() {
    const { store: { getBlogPersonalInfo } } = this.props;
    getBlogPersonalInfo({blogId: this.state.userId});
  }

	resetInfo = (nextUserId) => {
		const { store } = this.props;
		store.clear();
		this.setState({
      cardType: 1,
      userId: nextUserId
		});

		store.getBlogPersonalInfo({blogId: nextUserId});

		let { cardType } = this.state || {};
		if(!cardType) cardType = 1;
		if(cardType == 1) {
			store.getViewBlogList({
				userId: nextUserId
      });
		} else if(cardType == 2) {
			store.getMyBlogAttention({
				blogId: nextUserId,
				groupid: 'all'
			});
		} else if(cardType == 3) {
			store.getAttentionMesUsers({
				userId: nextUserId
			});
		}
  }
  
  getTemplate = () => {
    const listStyle = 'blog-list-line';
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (data) => {
          const { imageUrl, lastname, departmentName, jobTitle,userId } = data;
          return (
            <div className={listStyle}>
              <div className={`${listStyle}-userInfo`}>
                <Avatar userId={userId} style={{width:40, height:40}} />
                <div className={`${listStyle}-userInfo-content`}>
                  <span className='lastName text-wrap'>{lastname}</span>
                  <span className='departmentName text-wrap'>{departmentName}&nbsp;&nbsp;{jobTitle}</span>
                </div>
              </div>
            </div>
          )
        }
      }]
    }
    return newTemp;
  }

	// 统计信息tab
	getBasicInfoCard = (blogInfo, cardType) => {
		const { store, location: { pathname }  } = this.props;
    let he = blogInfo.sex === '0' ? getLabel('384494','他') : getLabel('384495','她');
    let userIdis = this.props.userId ? this.props.userId:this.state.userId;
		let isMe = blogInfo.currentUserId == userIdis;
		if (isMe) he = getLabel('130758','我');
		let basicInfoCard = [
      {
          id: 1,
          name: he + getLabel(384490,'的微博'),
          value: blogInfo.blogCount,
          color: '#4E91FE',
          onClick: () => {
						this.setState({
							cardType: 1
            });
            store.setEndDate();
						store.getViewBlogList({
							userId: blogInfo.userId
						});
          },
          isActive: cardType == 1,
      },
      {
        id: 2,
        name: he + getLabel(384497,'的关注'),
        value: blogInfo.myAttentionCount,
        color: '#32BC40',
        onClick: () => {
          this.setState({
						cardType: 2
					});
					store.getMyBlogAttention({
						blogId: blogInfo.userId,
						groupid: 'all'
          });
        },
        isActive: cardType == 2,
      },
      {
          id: 3,
          name: he + getLabel(384498,'的粉丝'),
          value: blogInfo.attentionMeCount,
          color: '#cc31ff',
          onClick: () => {
            this.setState({
							cardType: 3
						});
						store.getAttentionMesUsers({
							userId: blogInfo.userId
						});
          },
          isActive: cardType == 3,
      }  
		];
		return basicInfoCard;
	}

	// 内容部分
	getContent = (viewBlogId, cardType) => {
    const { store: { hisAttentionList, hisFansList, setChild, childId, getMyBlogAttention, getAttentionMesUsers, isNoData }, path, prefixCls } = this.props;
		if(cardType == 1) {
			return (
        <BlogComment replyStore={this.props.store}  storeName='hisBlog'/>
			);
		} else if(cardType == 2 || cardType == 3) { //2他的关注,3他的粉丝
      let list = cardType == 2 ? hisAttentionList : (cardType == 3 ? hisFansList : []);
			return isNoData ? renderNoData : (
				<div className={`${prefixCls}-content-list`}>
           <ListViewPage.Normal
              store={list}
              getDataCustom
              getTemplate={this.getTemplate}
              customHeight='100%'
              rowKey='userId'
              onRefresh={() => {
                if (cardType == 2)  getMyBlogAttention({blogId: this.state.userId,groupid: 'all'})
                else getAttentionMesUsers({userId: this.state.userId})
              }}
              onRowClick={(rowData) => {
                if (childId && childId === rowData.userId) {
                  this.history.go(-1);
                } else {
                  setChild(rowData.userId);
                  this.props.history.push(path+"/"+rowData.userId);
                }
              }}
           />
				</div>
			);
		}
  }


  goToSpecial = () => {
      this.props.history.push({pathname:"/userCenter/blogAttention/attention",query: { name : 'special' }});
  }

 
   render() {
    let { store: { blogInfo ,addSpecialUser,cancelSpecialUser}, prefixCls } = this.props;
    blogInfo = toJS(blogInfo);
    if (!blogInfo) {return renderLoading}
 
		else if (blogInfo.viewStatus == -1)
			return (
				<div className={`${prefixCls} blog-wuquanxian`}>
          <Result
            img={<Icon type="wuquanxian" />}
            message={<div>
              {getLabel('384491','你当前不具有对')}{blogInfo.username}
              {getLabel('384493','工作微博的查看权限，请联系对方将微博分享给你，或向他发关注申请！')}
            </div>}
          />
				</div>
			);
		else if (blogInfo.viewStatus == 0)
			return (
				<div className={`${prefixCls} blog-wuquanxian`}>
					<Result
            img={<Icon type="wuquanxian" />}
            message={<div>
              {getLabel('384491','你当前不具有对')}{blogInfo.username}
              {getLabel('384493','工作微博的查看权限，请联系对方将微博分享给你，或向他发关注申请！')}
            </div>}
            buttonText={<div className='noPermission'>
              <AttentionTool 
                isreceive={blogInfo.isreceive} 
                attentionStatus={blogInfo.attentionStatus} 
                islower={blogInfo.islower} 
                userId={blogInfo.userId} 
                callback={this.updateHisAttentionStatus}
              />
            </div>}
          />
				</div>
			);
   
		let { cardType } = this.state || {};
		if(!cardType) cardType = 1;
    let basicInfoCard = this.getBasicInfoCard(blogInfo, cardType);
    let userIdis = this.props.userId ? this.props.userId:this.state.userId;
    let isMe = blogInfo.currentUserId == userIdis;
    let isSp = blogInfo.specialStatus =='2';
    const userInfoClass = classnames(`${prefixCls}-user-info-msg`,
    {'active': isMe})
		return (
			<div className={prefixCls}  currentUserId={this.state.userId} >
        <div className={`${prefixCls}-user`}>
          <div className={`${prefixCls}-user-info`}>
            <WingBlank>
              <Avatar userId={blogInfo.userId} style={{width:60, height:60}}/>
              <div className={userInfoClass}>
                <div className={`${prefixCls}-user-info-msg-username`}>{blogInfo.username}</div>
                <div className={`${prefixCls}-user-info-msg-deptInfo`} style={{WebkitBoxOrient: 'vertical'}}>{blogInfo.deptName}&nbsp;&nbsp;{blogInfo.jobtitle}</div>
              </div>
              {
                !isMe ? (
                  <div className={`${prefixCls}-user-info-msgTool`}>
                      <div style={{"position": "absolute",
                          "right": "7%",
                          "top":" 28px",
                          "width": "100px"}}>
                    <AttentionTool 
                          isreceive={blogInfo.isreceive} 
                          attentionStatus={blogInfo.attentionStatus}
                          specialStatus={blogInfo.specialStatus}
                          islower={blogInfo.islower} 
                          userId={blogInfo.userId}
                          callback={this.updateHisAttentionStatus}/>
                      </div>
                      <div style={{"top": "25px",
                    "position": "absolute",
                    "right": "3%"}}>
                    <NewAttentionTool
                        isreceive={blogInfo.isreceive}
                        attentionStatus={blogInfo.attentionStatus}
                        islower={blogInfo.islower}
                        userId={blogInfo.userId}
                        specialStatus={blogInfo.specialStatus}
                        cancelSpecialUser={cancelSpecialUser}
                        callback={this.updateHisAttentionStatus}
                        goToSpecial={this.goToSpecial}
                        addSpecialUser={addSpecialUser}
                        type='hisblog'
                    />
                  </div>
                  </div>
                ) :""
              }
                       
            </WingBlank>
          </div>

          <Flex className={`${prefixCls}-user-count`}>
            {
              basicInfoCard.map((item,key) => {
                return (
                  <Flex.Item key={item.id} onClick={() => item.onClick()}>
                    <div className={`${prefixCls}-user-count-item ${item.isActive && 'active'}`}>
                      <span className={`${prefixCls}-user-count-item-value`} style={{color: item.color}}>{item.value}</span>
                      <span className={`${prefixCls}-user-count-item-name`}>{item.name}</span>
                    </div>
                    <div className={`${prefixCls}-user-count-line`}/>
                  </Flex.Item>
                )
              })
            }
          </Flex>
          <WhiteSpace />
        </div>

				<div className={`${prefixCls}-content`}>
          {this.getContent(blogInfo.userId, cardType)}
				</div>
			</div>
    )
	}
}